package com.kb.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.kb.common.MeException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@RefreshScope
public class GCutil {

    private static String clientId;
    private static String name;
    private static String localName;
    private static String password;
    private static String localPassword;
    private static String secret;
    private static String gcUrl;
    private static String localGcUrl;

    @Value("${gc.clientId}")
    public void setClientId(String clientId) {
        GCutil.clientId = clientId;
    }
    @Value("${gc.userName}")
    public void setName(String userName) {
        GCutil.name = userName;
    }
    @Value("${gc.localUserName}")
    public void setLocalName(String localName) {
        GCutil.localName = localName;
    }
    @Value("${gc.password}")
    public void setPassword(String password) {
        GCutil.password = password;
    }
    @Value("${gc.secret}")
    public void setSecret(String secret) {
        GCutil.secret = secret;
    }
    @Value("${gc.gcUrl}")
    public void setGcUrl(String gcUrl) {
        GCutil.gcUrl = gcUrl;
    }
    @Value("${gc.localGcUrl}")
    public void setLocalGcUrl(String localGcUrl) {
        GCutil.localGcUrl = localGcUrl;
    }
    @Value("${gc.localPassword}")
    public void setLocalPassword(String localPassword) {
        GCutil.localPassword = localPassword;
    }

    public static String getToken() throws MeException {
        //先从缓存拿
        String gcToken = GuavaCacheUtil.getToken("gcToken");
   //     gcToken = "Bearer 3f2f52357e1a47a4988389f44d826df2";

        if (StringUtils.isNotBlank(gcToken)){
            return gcToken;
        }
        // 定义请求参数
        String url = gcUrl+"/resource/openapi/v1/oauth2/token";
        String grantType = "password";
        // 构建请求参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("grantType", "password");
        paramMap.put("username", name);
        paramMap.put("password", password);

        // 添加自定义头部参数
        String nonce = RandomUtil.randomString(16);
        long timeMillis = System.currentTimeMillis();
        String signature = "client-id="+clientId+"&nonce="+nonce+"&timestamp="+timeMillis+"&key="+secret+"HN0YP9OZHktlHMwV0Bxvcg==";

        Map<String,String> headers = new HashMap<>();
        headers.put("client-id", clientId);
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        headers.put("timestamp", String.valueOf(timeMillis));
        headers.put("nonce", nonce);
        headers.put("signature", DigestUtil.md5Hex(signature).toUpperCase() );
//        System.out.println(DigestUtil.md5Hex(signature).toUpperCase());

        try {
            // 发送带有自定义头部参数的 GET 请求并获取响应
            // 发送 GET 请求
            HttpResponse response = HttpRequest.post(url)
                    .form(paramMap)
                    .addHeaders(headers)
                    .execute();

            String accessToken = null;
            try {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                accessToken = jsonObject.getJSONObject("data").getString("accessToken");
            } catch (Exception e) {
                throw new MeException(response.body());
            }
            String token = "Bearer "+accessToken;
            //存到缓存
            GuavaCacheUtil.saveToken("gcToken", token);
            return token;
        } catch (Exception e) {
            throw new MeException(e.getMessage());
        }
    }
    public static String getLocalGcToken() throws MeException {
        //先从缓存拿
        String gcToken = GuavaCacheUtil.getToken("localGcToken");
        //     gcToken = "Bearer 3f2f52357e1a47a4988389f44d826df2";

        if (StringUtils.isNotBlank(gcToken)){
            return gcToken;
        }
        // 定义请求参数
        String url = localGcUrl+"/to/api/base/system/auth/login";
        // 构建请求参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userType", 2);
        paramMap.put("password", localPassword);
        paramMap.put("email", localName);

        try {
            // 发送带有自定义头部参数的 GET 请求并获取响应
            // 发送 GET 请求
            HttpResponse response = HttpRequest.post(url)
                    .body(JSONUtil.toJsonStr(paramMap))
                    .execute();
            String accessToken = null;
            try {
                JSONObject jsonObject = JSONObject.parseObject(response.body());
                accessToken = jsonObject.getJSONObject("data").getString("accessToken");
            } catch (Exception e) {
                throw new MeException(response.body());
            }
            //存到缓存
            GuavaCacheUtil.saveToken("LocalGcToken", accessToken);
            return accessToken;
        } catch (Exception e) {
            throw new MeException(e.getMessage());
        }
    }
}
